package com.keter.checker.util;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * Created by gulx@neusoft.com on 2019/5/24.
 */
@Component
public class OKHttpUtil {

    @Value("${targets.timeout}")
    private int timeout;

    private OkHttpClient client;

    private OkHttpClient buildClient() {
        return new OkHttpClient.Builder()
                .addInterceptor(
                        chain -> {
                            Request request = chain.request();
                            Response response = chain.proceed(request);
                            return response;
                        })
                .connectTimeout( 2000, TimeUnit.MILLISECONDS)
                .readTimeout(timeout * 1000, TimeUnit.MILLISECONDS)
                .writeTimeout(timeout * 1000, TimeUnit.MILLISECONDS)
                .build();
    }

    public OkHttpClient client() {
        if (client == null) {
            client = buildClient();
        }
        return client;
    }
}
